package com.alix.paymoney.http;



import com.alix.paymoney.base.Url;
import com.alix.paymoney.utils.Loger;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by admin on 2017/2/27.
 */

public class HttpManager {
    private static HttpManager instance;
    //读超时长，单位：毫秒
    public static final int READ_TIME_OUT = 10000;
    //连接时长，单位：毫秒
    public static final int CONNECT_TIME_OUT = 10000;
    public static Retrofit retrofit;
    private static ApiService apiService;

    private HttpManager() {
    }

    public static HttpManager getInstance() {
        if (instance == null) {
            synchronized (HttpManager.class) {
                if (instance == null) {
                    instance = new HttpManager();
                    init();
                }
            }
        }
        return instance;
    }


    private static void init() {


        //拦截器,增加头部信息,重定向等,
        Interceptor headerInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {





                Request.Builder builder = chain.request().newBuilder();
                String s = chain.request().url().toString();
                Loger.e("访问地址"+s);

                Request build = builder.addHeader("Content-Type", "application/json;charset=utf-8")
                        .build();
                return chain.proceed(build);
            }
        };

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(READ_TIME_OUT, TimeUnit.MILLISECONDS)
                .connectTimeout(CONNECT_TIME_OUT, TimeUnit.MILLISECONDS)
                .addInterceptor(headerInterceptor)
                .retryOnConnectionFailure(true)
                .build();

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(Url.BASE_URL)
                .build();
        apiService = retrofit.create(ApiService.class);
    }

    public ApiService getApiService() {
        return apiService;
    }

    public void addQueue(Call call, final OnResponseListener onresponse) {

        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, retrofit2.Response response) {
                if (response.code() == 200) {

                    onresponse.Success(response.body());
                }else {
                    onresponse.onFailed(response.code(), response.message());
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                if (t instanceof ConnectException) {
                    onresponse.onException("网络不给力,请重试");
                } else if (t instanceof SocketTimeoutException) {
                    onresponse.onException("网络不给力,请重试");
                } else if (t instanceof UnknownHostException) {
                    onresponse.onException("网络不给力,请重试");
                } else {
                    onresponse.onException("连接异常");
                }
            }
        });
    }
}
